#include <map>
#include "ConnectReqHandler.h"
#include "BeginDualRelayHandler.h"

using namespace std;
using namespace log4cplus;

Logger ConnectReqHandler::log=GetLogger(LOG4CPLUS_TEXT("ConnectReqHandler"));

void ConnectReqHandler::CreateSocketPostProcess(ClientContext &client,OVERLAPPED *ovl,SOCKET sock)
{
	unsigned int clienSequenceNo=client.SequenceNo();
	map<string,string>::const_iterator iter=client.HttpRequest().Headers().find("Proxy-Connection");
	if(iter!=client.HttpRequest().Headers().end()&&iter->second==" Keep-Alive")
	{
		setsockopt(sock,SOL_SOCKET,SO_KEEPALIVE,reinterpret_cast<char*>(1),sizeof(BOOL));
	}
	client.SetDestSock(sock);
	LOG4CPLUS_DEBUG_FMT(log,LOG4CPLUS_TEXT("[Client%d]CONNECT request handler's server socket post process finished."),clienSequenceNo);
}

ITransHandler* ConnectReqHandler::GetNextHandler()
{
	return new BeginDualRelayHandler();
}

ITransHandler::ExecuteResultCode ConnectReqHandler::OnExecuteError(ClientContext &client,OVERLAPPED *ovl,ITransHandler::ExecuteResultCode executeResult)
{
	return executeResult;
}

ITransHandler::ExecuteResultCode ConnectReqHandler::OnConnected(ClientContext &client,OVERLAPPED *ovl)
{
	unsigned int clienSequenceNo=client.SequenceNo();
	::ZeroMemory(client.OVL(),sizeof(OVERLAPPED));
	string msg="HTTP/1.0 200 Connection established\r\nProxy-agent: PS3TransAgent\r\n\r\n";
	memcpy_s(client.Buffer()->buf,client.Buffer()->len,msg.c_str(),msg.size());
	client.WeakRefBuffer()->buf=client.Buffer()->buf;
	client.WeakRefBuffer()->len=msg.size();
	int result=::WSASend(client.SrcSock(),client.WeakRefBuffer(),1,NULL,0,client.OVL(),NULL);
	int errCode=::WSAGetLastError();
	if(result!=0&&errCode!=WSA_IO_PENDING)
	{
		LOG4CPLUS_ERROR_FMT(log,LOG4CPLUS_TEXT("[Client%d]Begin send connect message failed,error code:%d."),clienSequenceNo,errCode);
		return ITransHandler::ExecuteFatalError;
	}
	LOG4CPLUS_DEBUG_FMT(log,LOG4CPLUS_TEXT("[Client%d]Begin send connect message successed."),clienSequenceNo);
	return ITransHandler::ExecuteOK;
}